<script setup lang="ts">
import type {
  SysDeptTreeVo,
} from '#/system/dept'
import type {
  SysPostVo,
} from '#/system/post'
import type {
  SysRoleVo,
} from '#/system/role'
import type {
  SysUserQo,
} from '#/system/user'
import type { TreeInstance } from 'element-plus'
import {
  createSysUserApi,
  getSysUserDetailsApi,
  updateSysUserApi,
} from '@/api/system/user'
import { cloneDeep } from 'lodash'

interface OnCloseResolveType extends CloseResolveType {}
let onCloseResolve = function (_value: OnCloseResolveType) { }

const dialogRef = $ref<DialogInstance>()
const ruleFormRef = ref<FormInstance>()
let dialogModal = $ref<SysUserQo>({})
let dialogAction = $ref<DialogAction>('add')
let confirmLoading = $ref(false)
let dialogLoading = $ref(false)
let roleList = $ref<SysRoleVo[]>([])
let postList = $ref<SysPostVo[]>([])
let deptTree = $ref<SysDeptTreeVo[]>([])
let mainDeptTree = $ref<SysDeptTreeVo[]>([])
let mainExpandedKey = $ref<string[]>([])
const mainTreeRef = $ref<TreeInstance>()

const mainPostList = $computed(() => {
  return postList.filter(item => dialogModal.postIdList?.includes(item.id))
})

const rules = reactive<FormRules<SysUserQo>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' },
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
  ],
})
async function getDefaultModel() {
  return {
    sex: 1,
  } as SysUserQo
}
// 打开
async function showDialog(args: {
  title: string
  action?: DialogAction
  model: {
    id?: string
  }
  roleList: SysRoleVo[]
  postList: SysPostVo[]
  deptTree: SysDeptTreeVo[]
}) {
  const dialogRes = dialogRef!.openDialog<OnCloseResolveType>({
    title: args.title,
    size: 'medium',
  })

  ruleFormRef.value?.clearValidate()
  onCloseResolve = dialogRes.onCloseResolve

  roleList = args.roleList
  postList = args.postList
  deptTree = args.deptTree
  mainDeptTree = cloneDeep(args.deptTree)

  dialogAction = args.action ?? 'add'

  if (args.model.id) {
    dialogModal.id = args.model.id
  }

  if (args.action === 'add') {
    const defaultModel = await getDefaultModel()
    dialogModal = {
      ...defaultModel,
      ...args.model,
    }
  }
  else if (args.action === 'edit' || args.action === 'views') {
    await reflash()
  }

  mainTreeRef?.filter('')

  return await dialogRes.dialogPrm
}

async function reflash() {
  if (!dialogModal.id)
    return
  dialogLoading = true
  const res = await getSysUserDetailsApi(dialogModal.id)
  if (!res)
    return
  dialogLoading = false
  Object.assign(dialogModal, res.data)
  mainExpandedKey = [dialogModal.deptId] as any
}

// 确认
async function confirm(formEl: FormInstance | undefined) {
  if (!formEl)
    return
  await formEl.validate(async (valid) => {
    if (!valid) {
      return
    }
    confirmLoading = true
    if (dialogAction === 'add') {
      await createSysUserApi(dialogModal).finally(() => {
        confirmLoading = false
      })
    }
    else if (dialogAction === 'edit') {
      await updateSysUserApi(dialogModal).finally(() => {
        confirmLoading = false
      })
    }
    confirmLoading = false
    Message({
      type: 'success',
      message: `${DialogActionMap[dialogAction as DialogAction]}成功`,
    })
    onCloseResolve({ type: true })
  })
}

function mainDeptFilterMethod(val: string, data: SysDeptTreeVo) {
  if (!dialogModal.deptIdList)
    return false
  return dialogModal.deptIdList.includes(data.id as string)
}

watch(() => dialogModal.deptIdList, () => {
  mainTreeRef?.filter('')
  disableMainDeptTree()
})

// 只有选中的部门主部门才能选
function disableMainDeptTree() {
  function disabled(data: SysDeptTreeVo[]) {
    data.forEach((item) => {
      if (dialogModal.deptIdList?.includes(item.id as string)) {
        item.disabled = false
      }
      else {
        item.disabled = true
      }
      if (item.children) {
        disabled(item.children)
      }
    })
  }
  disabled(mainDeptTree)
}

// 取消
function cancel() {
  ruleFormRef.value?.clearValidate()
  onCloseResolve({ type: false })
}

defineExpose({ showDialog })
</script>

<template>
  <sy-dialog
    ref="dialogRef"
    :before-close="cancel"
    :hide-confirm="dialogAction === 'views'"
    :confirm-loading="confirmLoading"
    :disabled-confirm="dialogLoading"
    @confirm="confirm(ruleFormRef)"
  >
    <el-form
      ref="ruleFormRef"
      v-loading="dialogLoading"
      :model="dialogModal"
      :rules="rules"
      label-width="auto"
      status-icon
      un-grid="~ cols-2 gap-x-8"
      un-items-center
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="dialogModal.username"
          placeholder="请输入用户名"
          clearable
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>
      <el-form-item label="昵称" prop="name">
        <el-input
          v-model="dialogModal.name"
          placeholder="请输入昵称"
          clearable
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input
          v-model="dialogModal.phone"
          placeholder="请输入手机号码"
          clearable
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="dialogModal.password"
          placeholder="请输入密码"
          type="password"
          clearable
          show-password
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="dialogModal.email"
          placeholder="请输入邮箱"
          clearable
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>

      <el-form-item label="生日" prop="birthday">
        <el-date-picker
          v-model="dialogModal.birthday"
          placeholder="请选择生日"
          clearable
          style="width: 100%;"
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>

      <el-form-item label="机构" prop="deptIdList">
        <el-tree-select
          v-model="dialogModal.deptIdList"
          :data="deptTree"
          node-key="id"
          :render-after-expand="true"

          :default-expanded-keys="dialogModal.deptIdList"
          :props="{
            label: 'name',
          }"

          check-strictly multiple show-checkbox highlight-current
          @change="() => {
            dialogModal.deptId = null as any
          }"
        />
      </el-form-item>

      <el-form-item label="主机构" prop="deptId">
        <el-tree-select
          ref="mainTreeRef"
          v-model="dialogModal.deptId"
          :data="mainDeptTree"
          node-key="id"
          check-strictly
          :props="{
            label: 'name',
          }"
          :default-expanded-keys="mainExpandedKey"
          :filter-node-method="mainDeptFilterMethod"
          show-checkbox
        />
      </el-form-item>

      <el-form-item label="岗位" prop="postIdList">
        <el-select
          v-model="dialogModal.postIdList"
          multiple
          :disabled="dialogAction === 'views'"
          style="width: 100%;"
          placeholder="请选择岗位"
          filterable
          @change="() => {
            dialogModal.postId = null as any
          }"
        >
          <el-option
            v-for="item in postList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主岗位" prop="postId">
        <el-select
          v-model="dialogModal.postId"
          :disabled="dialogAction === 'views'"
          style="width: 100%;"
          filterable
          placeholder="请选择主岗位"
        >
          <el-option
            v-for="item in mainPostList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="角色" prop="roleIdList">
        <el-select
          v-model="dialogModal.roleIdList"
          multiple
          :disabled="dialogAction === 'views' || dialogModal.tenantAdmin"
          style="width: 100%;"
          placeholder="请选择角色"
        >
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="性别" prop="sex">
        <sy-dict
          v-model="dialogModal.sex"
          dict-type="user_sex"
          type="radio"
        />
      </el-form-item>

      <el-form-item
        label="备注"
        prop="remark"
        un-grid="col-span-2"
      >
        <el-input
          v-model="dialogModal.remark"
          type="textarea"
          placeholder="请输入备注"
          :disabled="dialogAction === 'views'"
        />
      </el-form-item>
    </el-form>
  </sy-dialog>
</template>

<style scoped></style>
